package user

import (
	"context"
	"fast-boot/app/api/admin/internal/svc"
	"fast-boot/app/api/admin/internal/types"
	"fast-boot/app/model"
	"fast-boot/common/xerr"
	"github.com/hwUltra/fb-tools/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type ChangePwdLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 修改用户密码
func NewChangePwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ChangePwdLogic {
	return &ChangePwdLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ChangePwdLogic) ChangePwd(in *types.SysUserChangePwdReq) (resp *types.SysUserFormResp, err error) {
	user := model.SysUserModel{}
	l.svcCtx.GormClient.GormDb.First(&user, in.UserId)
	if user.Id == 0 {
		return nil, xerr.NewErrMsg("用户不存在")
	}
	if len(in.Password) > 0 {
		user.Password = utils.PasswordEncrypt(l.svcCtx.Config.Salt, in.Password)
	}

	if l.svcCtx.GormClient.GormDb.Save(&user).Error != nil {
		return nil, err
	}

	return &types.SysUserFormResp{}, nil
}
